package cn.cyan.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @author LWQ
 * @Description:
 */
@RestController
public class SendController {

    private static final Logger logger = LoggerFactory.getLogger(SendController.class);

    @RequestMapping(value = "/dfs/12/json/{fileName}", method = RequestMethod.POST)
    @ResponseBody
    public void getVehicleId(HttpServletRequest req, @PathVariable String fileName
    ) throws Exception {

        SimpleDateFormat dfsss = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        JSONObject parseObject = new JSONObject();
        String string = fileName.split("@")[0];
        List<MultipartFile> files = ((MultipartHttpServletRequest) req).getFiles("binFile");
        JSONObject obj = JSON.parseObject(new String(files.get(0).getBytes(), StandardCharsets.UTF_8));
        File file = new File("files/" + string + ".json");
        // 使用 FileWriter 和 BufferedWriter 进行写入
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file, StandardCharsets.UTF_8))) {
            // 将 JSONObject 转成字符串并写入文件
            writer.write(obj.toJSONString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        logger.info("===>文件名称:[{}] 收到消息:[{}]", fileName, obj.toJSONString());
    }

}
